package com.google.code.p.restrpc.spring.metadata;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

import com.google.code.p.restrpc.spring.InvalidMetadataException;

public class CachedRpcAttributeSource implements RpcAttributeSource {
    
    private static final Object DUMMY_OBJECT = new Object();
    
    private Map<Class, SoftReference<Object>> repository = new HashMap<Class, SoftReference<Object>>();
    
    private RpcAttributeSource source;
    
    public CachedRpcAttributeSource(RpcAttributeSource source) {
        super();
        this.source = source;
    }
    
    public RpcMetadata getRpcMetadata(Class beanClass) throws InvalidMetadataException {
        Object result = repository.get(beanClass);
        if (null == result) {
            result = source.getRpcMetadata(beanClass);
            if (null == result) {
                repository.put(beanClass, new SoftReference(DUMMY_OBJECT));
            }
            else {
                repository.put(beanClass, new SoftReference(result));
            }
        }
        if (DUMMY_OBJECT == result) {
            return null;
        }
        return (RpcMetadata) result;
    }
}
